package com.xxx.sso.ctrl;

import com.xxx.sso.base.BaseCtrl;
import com.xxx.sso.base.BaseService;
import com.xxx.sso.consts.CookieConst;
import com.xxx.sso.consts.RedisConst;
import com.xxx.sso.entity.User;
import com.xxx.sso.service.UserService;
import com.xxx.sso.util.Result;
import com.xxx.sso.util.ResultBuilder;
import com.xxx.sso.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * 用户接口层
 * @author caiwl
 * @date 2020/4/30 9:34
 */
@RestController
@RequestMapping("/user")
public class UserCtrl extends BaseCtrl<User> {
    @Autowired
    private UserService userService;

    /**
     * 登录校验
     * @param request
     * @param token
     * @return
     */
    @PostMapping("/isLogin")
    public Result isLogin(HttpServletRequest request, String token) {
        boolean logged = false;
        Cookie[] cookies;
        // 延迟赋值，延迟申请空间
        if ((cookies = request.getCookies()) != null) {
            for (Cookie cookie : cookies) {
                if (CookieConst.NAME.equals(cookie.getName())) {
                    logged = userService.isLogin(cookie.getValue());
                    break;
                }
            }
        }
        if (!logged && StringUtil.nonEmpty(token)) {
            logged = userService.isLogin(token);
        }

        return ResultBuilder.okWithObj(logged);
    }

    /**
     * 登录
     * @param user
     * @return
     */
    @PostMapping("/login")
    public Result login(HttpServletRequest request, @Validated User user) {
        return userService.login(request.getSession().getId(), user);
    }

    /**
     * 登录后获取个人基本信息
     * @param id
     * @return
     */
    @PostMapping("/baseInfo")
    public Result baseInfo(@RequestAttribute(RedisConst.ATTR_NAME_USERID) Long id) {
        return ResultBuilder.okWithObj(userService.baseInfo(id));
    }

    /**
     * 退出
     * @param token
     * @return
     */
    @PostMapping("/logout")
    public Result logout(@RequestAttribute(RedisConst.ATTR_NAME_TOKEN) String token) {
        userService.logout(token);
        return ResultBuilder.ok();
    }

    /**
     * 条件+分页查询
     * @param page
     * @return
     */
    @Override
    @GetMapping
    public Result page(User user, @PageableDefault(sort = {"username"}) Pageable page) {
        return super.page(user, page);
    }

    @Override
    public BaseService<User> service() {
        return userService;
    }
}
